from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.views import Response
from utils.handle_logger import logger


def exception_handler(exc, context):
    request = context.get('request')
    try:
        username = request.user.username
        if not username:
            username = '游客用户'
    except Exception:
        username = '游客用户'
    logger.error(
        f"用户:[{username}],请求方式:[{request.method}],路径:[{request.get_full_path()}],访问视图:[{str(context.get('view'))}],报错:[{str(exc)}]")
    res = drf_exception_handler(exc, context)
    if res:
        response = {'code': 20001, 'msg': res.data.get('detail')}
    else:
        response = {'code': 20002, 'msg': str(exc)}
    return Response(response)
